package org.hbkj.springbootmybatis.controller;

import org.hbkj.springbootmybatis.entity.OrderDo;
import org.hbkj.springbootmybatis.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 用户查询自己的订单
    @GetMapping("/user/{userId}")
    public List<OrderDo> getOrdersByUserId(@PathVariable Integer userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        return orderService.getOrdersByUserId(userId);
    }

    // 管理员查询所有订单（添加权限校验）
    @GetMapping("/admin/all")
    public List<OrderDo> getAllOrders(@RequestHeader("Authorization") String token) {
        validateAdminToken(token);
        return orderService.getAllOrders();
    }

    // 创建订单
    @PostMapping("/create")
    @ResponseStatus(HttpStatus.CREATED)
    public int createOrder(@RequestBody OrderDo order) {
        validateOrderRequest(order);
        return orderService.createOrder(order);
    }

    // 更新订单状态
    @PutMapping("/status")
    public String updateOrderStatus(@RequestHeader("Authorization") String token,
                                    @RequestParam String orderId,
                                    @RequestParam String orderStatus) {
        validateAdminToken(token);
        validateOrderId(orderId);
        validateOrderStatus(orderStatus);

        int result = orderService.updateOrderStatus(orderId, orderStatus);
        if (result > 0) {
            return "状态更新成功";
        } else {
            return "状态更新失败";
        }
    }

    // 删除订单 - 普通用户只能删除自己的待付款订单
    @DeleteMapping("/{orderId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteOrder(@RequestHeader("Authorization") String token,
                            @PathVariable String orderId,
                            @RequestParam(required = false) Integer userId) {
        // 管理员可以删除任意订单
        if (isAdminToken(token)) {
            validateOrderId(orderId);
            orderService.deleteOrder(orderId);
            return;
        }

        // 普通用户只能删除自己的订单
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("普通用户删除订单必须提供用户ID");
        }

        // 验证订单归属
        OrderDo order = orderService.getOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("订单不存在"));

        if (!order.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权删除此订单");
        }

        orderService.deleteOrder(orderId);
    }

    // 根据订单ID查询单个订单
    @GetMapping("/{orderId}")
    public OrderDo getOrderById(@PathVariable String orderId) {
        validateOrderId(orderId);
        return orderService.getOrderById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
    }

    // 统计用户订单数量
    @GetMapping("/user/{userId}/count")
    public int countOrdersByUserId(@PathVariable Integer userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        return orderService.countOrdersByUserId(userId);
    }

    // 根据状态查询订单
    @GetMapping("/status/{orderStatus}")
    public List<OrderDo> getOrdersByStatus(@PathVariable String orderStatus) {
        validateOrderStatus(orderStatus);
        return orderService.getOrdersByStatus(orderStatus);
    }

    // 权限验证方法
    private void validateAdminToken(String token) {
        if (!isAdminToken(token)) {
            throw new RuntimeException("无权限访问");
        }
    }

    private boolean isAdminToken(String token) {
        return token != null && token.startsWith("admin_");
    }

    // 订单ID校验
    private void validateOrderId(String orderId) {
        if (orderId == null || orderId.trim().isEmpty()) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
    }

    // 订单状态校验
    private void validateOrderStatus(String orderStatus) {
        if (orderStatus == null || orderStatus.trim().isEmpty()) {
            throw new IllegalArgumentException("订单状态不能为空");
        }
        // 验证状态是否在合法值范围内
        List<String> validStatus = List.of(
                "待付款", "待发货", "已发货", "已完成", "申请退款", "已退款"
        );
        if (!validStatus.contains(orderStatus)) {
            throw new IllegalArgumentException("无效的订单状态");
        }
    }

    // 订单请求校验
    private void validateOrderRequest(OrderDo order) {
        if (order == null) {
            throw new IllegalArgumentException("订单信息不能为空");
        }
        if (order.getUserId() == null || order.getUserId() <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        if (order.getGoodsId() == null || order.getGoodsId() <= 0) {
            throw new IllegalArgumentException("商品ID不能为空且必须大于0");
        }
        if (order.getQuantity() == null || order.getQuantity() <= 0) {
            throw new IllegalArgumentException("商品数量不能为空且必须大于0");
        }
    }
}